package 剑指offer;

import java.util.ArrayList;
import java.util.List;

public class _29 {
    public static int[] spiralOrder(int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return new int[0];
        }
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;
        List<Integer> result = new ArrayList<Integer>();
        int[] res = new int[matrix.length * matrix[0].length];
        int count = 0;
        while(count < (matrix.length) * (matrix[0].length)){
            int flag = 0;
            for(int i = left; i <= right; i++){
                res[count] = matrix[top][i];
                count++;
            }
            for(int j = top + 1; j <= bottom; j++){
                res[count] = matrix[j][right];
                count++;
            }
            if(top != bottom && right != left){
                for(int i = right - 1; i >= left; i--){
                    res[count] = matrix[bottom][i];
                    count++;
                }
                for(int j = bottom - 1; j > top; j--){
                    res[count] = matrix[j][left];
                    count++;
                }
            }
            top++;
            bottom--;
            left++;
            right--;
        }
        return res;
    }
}
